package com.pds.web.app.service.impl;

import com.pds.common.core.domain.entity.SysDictData;
import com.pds.common.core.domain.entity.SysRole;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.exception.base.BaseException;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.mapper.FileUploadMapper;
import com.pds.system.mapper.SysDictDataMapper;
import com.pds.system.service.ISysDictTypeService;
import com.pds.utils.FileUtil;
import com.pds.web.app.mapper.AppStationOpsMapper;
import com.pds.web.app.service.IAppStationOpsService;
import com.pds.web.company.domain.PdsCompanyStationOpsForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppStationOpsServiceImpl implements IAppStationOpsService {

    private static Logger log = LoggerFactory.getLogger(AppStationOpsServiceImpl.class);
    /**废水、废气表单类型*/
    private static final String TABLE_TYPE="table_type";
    /**排放类型*/
    private static final String EMISSION_TYPE="emission_type";



    @Autowired
    private AppStationOpsMapper stationOpsMapper;
    @Autowired
    FileUploadMapper fileUploadMapper;
    @Autowired
    ISysDictTypeService dictTypeService;
    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 新建运维表单
     *
     * @param form
     * @return
     */
    @Override
    public PdsCompanyStationOpsForm createForm(PdsCompanyStationOpsForm form) {
        log.info("新建运维表单:{}", form);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        form.setCreateBy(user.getNickName());
        form.setOpsEngineer(user.getUserId());
        form.setStatus(0);
        stationOpsMapper.insert(form);
        return form;
    }

    /**
     * 查询运维表单详情
     *
     * @param id
     * @return
     */
    @Override
    public PdsCompanyStationOpsForm getFromDetail(Long id) {
        PdsCompanyStationOpsForm form = stationOpsMapper.selectById(id);
        //台账文件查询
        if(StringUtils.isNotEmpty(form.getLedgerId())){
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(form.getLedgerId().split(","));
            if (fileUploads != null && fileUploads.size() > 0) {
                List<Map> ledger = new ArrayList<>(fileUploads.size());
                for (FileUpload fileUpload : fileUploads) {
                    ledger.add(FileUtil.structureFile(fileUpload));
                }
                form.setLedger(ledger);
            }
        }
        String emissionTypeName = dictDataMapper.selectDictLabel(EMISSION_TYPE, form.getEmissionType());
        String tableTypeName = dictDataMapper.selectDictLabel(TABLE_TYPE, String.valueOf(form.getTableType()));
        form.setEmissionTypeName(emissionTypeName);
        form.setTableTypeName(tableTypeName);
        return form;
    }

    /**
     * 运维签到签退
     *
     * @param map - id 运维表单id
     *            - type 1签到 2 签退
     *            - fileId 拍照照片id
     *            - place 经纬度
     * @return
     */
    @Transactional
    @Override
    public void checkIn(Map map) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        long id = Long.parseLong(String.valueOf(map.get("id")));
        String type = String.valueOf(map.get("type"));
        String fileId = String.valueOf(map.get("fileId"));
        String place = String.valueOf(map.get("place"));
        PdsCompanyStationOpsForm form = new PdsCompanyStationOpsForm();
        form.setId(id);
        form.setUpdateBy(user.getNickName());
        PdsCompanyStationOpsForm formDB = stationOpsMapper.selectById(id);
        if("1".equals(type)){
            if(formDB.getStatus()>0){
                throw new BaseException("已签到，不能重复签到");
            }
            form.setOpsStartImgId(fileId);
            form.setOpsStartPlace(place);
            form.setOpsStartTime(new Date());
            form.setStatus(1);
        }else if("2".equals(type)){
            if(formDB.getStatus()>1){
                throw new BaseException("已签退，不能重复签退");
            }
            form.setOpsEndImgId(fileId);
            form.setOpsEndPlace(place);
            form.setOpsEndTime(new Date());
            form.setStatus(2);
        }else{
            throw new BaseException("非法操作");
        }
        stationOpsMapper.update(form);
    }

    /**
     * 提交台账
     * @param map - id 运维表单id
     *            - ledgerId 台账附件id
     * @return
     */
    @Override
    public void formSumit(Map map) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        long id = Long.parseLong(String.valueOf(map.get("id")));
        String ledgerId = String.valueOf(map.get("ledgerId"));
        PdsCompanyStationOpsForm form = new PdsCompanyStationOpsForm();
        form.setId(id);
        form.setLedgerId(ledgerId);
        form.setLedgerTime(new Date());
        form.setUpdateBy(user.getNickName());
        form.setStatus(3);
        stationOpsMapper.update(form);
    }

    /**
     * 删除表单
     *
     * @param id
     */
    @Override
    public void deleteForm(Long id) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PdsCompanyStationOpsForm form = new PdsCompanyStationOpsForm();
        form.setId(id);
        form.setUpdateBy(user.getNickName());
        form.setStatus(5);
        stationOpsMapper.update(form);
    }

    /**
     * APP首页：工作情况、待办
     * @param type week本周、month本月、year本年
     * @return
     */
    @Override
    public Map getIndexData(String type) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        Map map = DateUtils.getTimePeriod(type);
        map.put("userId",user.getUserId());
        Map result = new HashMap<>(8);
        //工作情况
        List<Map> list = stationOpsMapper.selectTaskCount(map);
        //进行中 表单状态：0：未签到，1：已签到，2：已签退、3已提交、4已评分
        List<Map> ongoingList = list.stream().filter(item -> "0".equals(item.get("status").toString())
                || "1".equals(item.get("status").toString()) || "2".equals(item.get("status").toString())).collect(Collectors.toList());
        List<Map> scoreList = list.stream().filter(item -> "3".equals(item.get("status").toString())).collect(Collectors.toList());
        result.put("totalNum",list.size());
        result.put("ongoingNum",ongoingList.size());
        result.put("scoreNum",scoreList.size());
        result.put("finishNum",list.size()-ongoingList.size()-scoreList.size());
        //待办列表，与上面统计无关，显示全部
        Map condition = new HashMap<>();
        if(role.contains("environmentaloperation")||role.contains("admin")){
            // 生态环境局-运维任务负责人
            condition.put("userId", -1);
        }else {
            condition.put("userId", user.getUserId());
        }
        List<Map> dataList = stationOpsMapper.selectTaskCount(condition);
        if(!role.contains("environmentaloperation")&&!role.contains("admin")){
            dataList = dataList.stream().filter(item -> "0".equals(item.get("status").toString())
                    || "1".equals(item.get("status").toString()) || "2".equals(item.get("status").toString())).collect(Collectors.toList());
        }
        result.put("ongoingList",dataList);

        //废水废气表单类型
        List<SysDictData> gasTableType = dictTypeService.selectDictDataByType(TABLE_TYPE);
        result.put("tableType",gasTableType);

        //所管站房
        List<Map> stationList =  stationOpsMapper.selectStationByUser(user.getUserId());
        result.put("stationList",stationList);

        return result;
    }
}
